package com.niit.drugsmanager.controller;

import com.niit.drugsmanager.entity.AdministrativeRegion;
import com.niit.drugsmanager.entity.RealNameAuth;
import com.niit.drugsmanager.entity.User;
import com.niit.drugsmanager.service.AdministrativeRegionService;
import com.niit.drugsmanager.service.RealNameService;
import com.niit.drugsmanager.utils.SessionUtils;
import jakarta.servlet.http.HttpSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.niit.drugsmanager.service.UserService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/api/real_name_auth")
public class RealNameAuthController {
    @Autowired
    private UserService userService;

    @Autowired
    private RealNameService realNameService;

    @Autowired
    private AdministrativeRegionService administrativeRegionService;

    @PostMapping("/save")
    public String saveAuth(
            @RequestParam("name") String name,
            @RequestParam("gender") String gender,
            @RequestParam("phone") String phone,
            @RequestParam("idCard") String idCard,
            @RequestParam("birthday") @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
            @RequestParam("administrativeRegion.code") Integer code,
            @RequestParam("addressDetail") String addressDetail,
            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
            RedirectAttributes redirectAttributes,
            HttpSession session) {
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b0001);
        if(!flag1) return "redirect:/api/user/ban";

        try {
            RealNameAuth realNameAuth = new RealNameAuth();
            RealNameAuth realNameAuthByUserId = realNameService.getRealNameAuthByUserId(user.getId());
            if(validateFile(avatar)) {
                byte[] avatarBytes = avatar.getBytes();
                if(realNameAuthByUserId == null) {
                    realNameAuth.setAvatarBlob(avatarBytes);
                    realNameAuth.setAvatarBase64(Base64.getEncoder().encodeToString(avatarBytes));
                    session.setAttribute("avatar", realNameAuth.getAvatarBase64());
                }else {
                    realNameAuthByUserId.setAvatarBlob(avatarBytes);
                    realNameAuthByUserId.setAvatarBase64(Base64.getEncoder().encodeToString(avatarBytes));
                    session.setAttribute("avatar", realNameAuthByUserId.getAvatarBase64());
                }
            }

            if (realNameAuthByUserId == null) {
                realNameAuth.setUser(user);
                realNameAuth.setName(name);
                realNameAuth.setGender(gender);
                realNameAuth.setPhone(phone);
                realNameAuth.setIdCard(idCard);
                realNameAuth.setBirthday(birthday);
                AdministrativeRegion administrativeRegionByCode = administrativeRegionService.findAdministrativeRegionByCode(code);
                realNameAuth.setAdministrativeRegion(administrativeRegionByCode);
                realNameAuth.setAddressDetail(addressDetail);

                realNameAuth.setCreateTime(LocalDateTime.now());
                realNameService.saveRealNameAuth(realNameAuth);
                redirectAttributes.addFlashAttribute("successMessage", "实名认证成功");
            } else {
                realNameAuthByUserId.setUser(user);
                realNameAuthByUserId.setName(name);
                realNameAuthByUserId.setGender(gender);
                realNameAuthByUserId.setPhone(phone);
                realNameAuthByUserId.setIdCard(idCard);
                realNameAuthByUserId.setBirthday(birthday);
                AdministrativeRegion administrativeRegionByCode = administrativeRegionService.findAdministrativeRegionByCode(code);
                realNameAuthByUserId.setAdministrativeRegion(administrativeRegionByCode);
                realNameAuthByUserId.setAddressDetail(addressDetail);

                realNameAuthByUserId.setUpdateTime(LocalDateTime.now());
                realNameService.saveRealNameAuth(realNameAuthByUserId);
                redirectAttributes.addFlashAttribute("successMessage", "实名修改成功");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "操作失败: " + e.getMessage());
        }
        return "redirect:/api/real_name_auth";
    }

    @GetMapping
    public String query(
            RedirectAttributes redirectAttributes,
            Model model,
            HttpSession session){
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b0001);
        if(!flag1) return "redirect:/api/user/ban";

        RealNameAuth realNameAuthByUserId = Optional.ofNullable(realNameService.getRealNameAuthByUserId(user.getId())).orElse(new RealNameAuth());
        model.addAttribute("authData", realNameAuthByUserId);
        return "/real_name_auth/index";
    }

    @GetMapping("/export-excel")
    public ResponseEntity<byte[]> exportExcel(HttpSession session) throws IOException {
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) {
            return ResponseEntity.status(HttpStatus.FOUND)
                    .header(HttpHeaders.LOCATION, "/api/user/login")
                    .build();
        }


        //权限检查
        boolean flag1 = user.hasRole(0b0101);
        if(!flag1) {
            return ResponseEntity.status(HttpStatus.FOUND)
                    .header(HttpHeaders.LOCATION, "/api/user/non-permission")
                    .build();
        }

        List<RealNameAuth> realNameAuths = realNameService.findAllRealNameAuth();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("User Profiles");

        Row headerRow = sheet.createRow(0);
        // 将这里的headers数组改名为headerNames，避免与HTTP头变量冲突
        String[] headerNames = {"ID", "用户ID", "姓名", "性别", "手机号码", "出生日期", "身份证号码", "籍贯", "详细地址","创建时间", "更新时间","头像"};
        for (int i = 0; i < headerNames.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headerNames[i]);
        }

        int rowNum = 1;
        for (RealNameAuth profile : realNameAuths) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(profile.getId());
            row.createCell(1).setCellValue(profile.getUser().getId());
            row.createCell(2).setCellValue(profile.getName());
            row.createCell(3).setCellValue(profile.getGender());
            row.createCell(4).setCellValue(profile.getPhone());
            row.createCell(5).setCellValue(profile.getBirthday().toString());
            row.createCell(6).setCellValue(profile.getIdCard());
            row.createCell(7).setCellValue(profile.getAdministrativeRegion().getNameChain().replace(".", " "));
            row.createCell(8).setCellValue(profile.getAddressDetail());
            row.createCell(9).setCellValue(profile.getCreateTime().toString());
            row.createCell(10).setCellValue(profile.getUpdateTime().toString());
            if (profile.getAvatarBlob() != null) {
                int pictureIdx = workbook.addPicture(profile.getAvatarBlob(), Workbook.PICTURE_TYPE_JPEG);
                CreationHelper helper = workbook.getCreationHelper();
                Drawing<?> drawing = sheet.createDrawingPatriarch();
                ClientAnchor anchor = helper.createClientAnchor();
                anchor.setCol1(11);
                anchor.setRow1(rowNum - 1);
                Picture pict = drawing.createPicture(anchor, pictureIdx);
                pict.resize();
            } else {
                row.createCell(11).setCellValue("无图片");
            }
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        // 这里的headers变量保持不变，它是HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "user_profiles.xlsx");

        return ResponseEntity.ok()
                .headers(headers)
                .body(outputStream.toByteArray());
    }

    private boolean validateFile(MultipartFile file) {
        // 验证类型
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
            return false;
        }

        // 验证大小
        if (file.getSize() > 2 * 1024 * 1024) {
            return false;
        }

        return true;
    }
}
